Code
library(tidyverse)
Tony Duan
October 10, 2022
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
按照1个变量汇总。并添加占比
# A tibble: 3 × 4
cyl row_record total_hp total_hp_share
<dbl> <int> <dbl> <dbl>
1 4 11 909 0.19
2 6 7 856 0.18
3 8 14 2929 0.62
按照2个变量汇总。并添加子分组占比
# A tibble: 5 × 5
# Groups: cyl [3]
cyl vs row_record total_hp total_hp_share
<dbl> <dbl> <int> <dbl> <dbl>
1 4 0 1 91 0.1
2 4 1 10 818 0.9
3 6 0 3 395 0.46
4 6 1 4 461 0.54
5 8 0 14 2929 1
按照2个变量汇总。并添加总占比
# A tibble: 5 × 5
cyl vs row_record total_hp total_hp_share
<dbl> <dbl> <int> <dbl> <dbl>
1 4 0 1 91 0.02
2 4 1 10 818 0.17
3 6 0 3 395 0.08
4 6 1 4 461 0.1
5 8 0 14 2929 0.62
---
title: "汇总表格并添加占比"
author: "Tony Duan"
date: "2022-10-10"
categories: [news]
execute:
warning: false
error: false
format:
html:
code-fold: show
code-tools: true
---
```{r}
library(tidyverse)
```
## 汇总表格
```{r}
head(mtcars)
```
按照1个变量cyl汇总。算了观察数量row_record,wt总数,wt总数占比
```{r}
mtcars %>% group_by(cyl) %>% summarise(row_record=n(),total_wt=sum(wt)) %>%
mutate(total_wt_share = round(total_wt / sum(total_wt),2))
```
按照2个变量cyl,gear汇总。算了观察数量row_record,wt总数,wt总数子分组占比
```{r}
mtcars %>% group_by(cyl,gear) %>% summarise(row_record=n(),total_wt=sum(wt)) %>%
mutate(total_wt_share = round(total_wt / sum(total_wt),2))
```
按照2个变量cyl,gear汇总。算了观察数量row_record,wt总数,wt总数总占比
```{r}
mtcars %>% group_by(cyl,gear) %>% summarise(row_record=n(),total_wt=sum(wt)) %>%
ungroup() %>%
mutate(total_wt_share = round(total_wt / sum(total_wt),2))
```
## Reference